from db_utils import con_my_sql
import pymysql
import gm_salt_sm3
from config import config_instance


# 获取登录验证数据库连接配置并使用
login_verify_conn = pymysql.connect(**config_instance.login_verify_conn_config)

def verify_user_login(email,name,pwd):
    user_data = get_user_by_email(email)
    if user_data:
        user_name = user_data['Username']
        if user_name == name:
            password_hash = user_data['PasswordHash']
            salt = user_data['Salt']
            result = gm_salt_sm3.hmac_verify_password(pwd, salt,password_hash)
            if result:
                return True,user_data
    return False,None

def get_user_by_id(user_id):
    """
    根据用户ID获取用户信息。

    :param user_id: 用户ID
    :return: 如果找到用户，返回用户字典；否则返回None
    """
    sql_code = "SELECT * FROM users WHERE UserID = %s"
    cursor_ans = con_my_sql(login_verify_conn, sql_code, (user_id,))

    if isinstance(cursor_ans, tuple) and issubclass(cursor_ans[0], Exception):
        print(f"Error getting user by id: {cursor_ans[1]}")
        return None
    else:
        if cursor_ans:
            user_data = cursor_ans[0]
        else:
            user_data = None
        return user_data

def get_user_by_email(email):
    """
    根据用户邮箱获取用户信息。

    :param email: 用户邮箱地址
    :return: 如果找到用户，返回用户字典；否则返回None
    """
    user_data = None
    try:
        sql_code = "SELECT * FROM users WHERE Email = %s"
        cursor_ans = con_my_sql(login_verify_conn, sql_code, (email,))
        if cursor_ans:
            user_data = cursor_ans[0]
    except Exception as ex:
        print(ex)
    return user_data

